import { Router } from "express";
import jwt from 'jsonwebtoken';
import { patientService } from '../services/mongodb-service';

const router = Router();

// 患者数据改为使用 MongoDB（见 Patient 模型与 patientService）

// 环境变量密钥
const PATIENT_AUTH_SECRET = process.env.PATIENT_AUTH_SECRET || 'patient-secret-key-2024';

// 工具函数：生成患者JWT token（expiresIn 以秒为单位）
function generatePatientToken(userId: string, role: 'patient' | 'family' | 'guest', expiresInSeconds: number = 30 * 24 * 60 * 60): string {
  const payload = {
    userId,
    role,
    type: 'patient',
    permissions: getPatientPermissions(role)
  };

  return jwt.sign(payload, PATIENT_AUTH_SECRET, { expiresIn: expiresInSeconds });
}

// 获取患者角色权限
function getPatientPermissions(role: string): string[] {
  const permissions: Record<string, string[]> = {
    'patient': ['read:own_data', 'create:appointment', 'read:drugs', 'create:location_request'],
    'family': ['read:family_data', 'create:appointment', 'read:drugs'],
    'guest': ['read:public_data', 'read:drugs']
  };
  return permissions[role] || permissions['guest'];
}

// 验证微信code（模拟实现）
async function verifyWechatCode(code: string): Promise<{ openid: string; sessionKey: string } | null> {
  // 实际实现中应该调用微信API
  // const response = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
  //   params: {
  //     appid: WECHAT_APPID,
  //     secret: WECHAT_SECRET,
  //     js_code: code,
  //     grant_type: 'authorization_code'
  //   }
  // });
  
  // 模拟返回
  return {
    openid: `mock_openid_${Date.now()}`,
    sessionKey: `mock_session_${Date.now()}`
  };
}

// 微信授权登录
router.post("/wechat-login", async (req, res) => {
  try {
    const { code, userInfo } = req.body;
    
    if (!code) {
      return res.status(400).json({
        success: false,
        message: "微信授权码不能为空"
      });
    }

    // 验证微信code，获取openid
    const wechatData = await verifyWechatCode(code);
    if (!wechatData) {
      return res.status(400).json({
        success: false,
        message: "微信授权验证失败"
      });
    }

    // 查找或创建患者用户（MongoDB）
    let patient = await patientService.getPatientByOpenId(wechatData.openid);
    if (!patient) {
      const patientId = `patient_${Date.now()}`;
      patient = await patientService.createPatient({
        patientId,
        openid: wechatData.openid,
        name: userInfo?.nickName || '微信用户',
        avatar: userInfo?.avatarUrl || '',
        isVerified: false,
        role: 'patient'
      });
    }

    // 生成患者专用token
    const token = generatePatientToken(patient.patientId, patient.role);

    res.json({
      success: true,
      data: {
        accessToken: token,
        tokenType: "Bearer",
        expiresIn: 30 * 24 * 60 * 60, // 30天
        user: {
          id: patient.patientId,
          name: patient.name,
          avatar: patient.avatar,
          role: patient.role,
          isVerified: patient.isVerified,
          permissions: getPatientPermissions(patient.role)
        }
      }
    });

    console.log(`[患者登录] 微信用户: ${patient.name} (${patient.patientId})`);

  } catch (error: any) {
    console.error("微信登录错误:", error);
    res.status(500).json({
      success: false,
      message: "登录服务异常"
    });
  }
});

// 手机号登录
router.post("/phone-login", async (req, res) => {
  try {
    const { phone, verifyCode, name, idCard } = req.body;
    
    if (!phone || !verifyCode) {
      return res.status(400).json({
        success: false,
        message: "手机号和验证码不能为空"
      });
    }

    // 验证码验证（模拟实现）
    if (verifyCode !== '123456') {
      return res.status(400).json({
        success: false,
        message: "验证码错误"
      });
    }

    // 查找或创建患者用户（MongoDB）
    let patient = await patientService.getPatientByPhone(phone);
    if (!patient) {
      const patientId = `patient_${Date.now()}`;
      patient = await patientService.createPatient({
        patientId,
        phone,
        name: name || '患者用户',
        idCard,
        isVerified: !!idCard,
        role: 'patient'
      });
    }

    // 生成患者专用token
    const token = generatePatientToken(patient.patientId, patient.role);

    res.json({
      success: true,
      data: {
        accessToken: token,
        tokenType: "Bearer",
        expiresIn: 30 * 24 * 60 * 60, // 30天
        user: {
          id: patient.patientId,
          name: patient.name,
          phone: patient.phone,
          role: patient.role,
          isVerified: patient.isVerified,
          permissions: getPatientPermissions(patient.role)
        }
      }
    });

    console.log(`[患者登录] 手机用户: ${patient.name} (${patient.phone})`);

  } catch (error: any) {
    console.error("手机登录错误:", error);
    res.status(500).json({
      success: false,
      message: "登录服务异常"
    });
  }
});

// 游客访问
router.post("/guest-access", async (req, res) => {
  try {
    const { deviceId } = req.body;
    
    const guestId = `guest_${Date.now()}`;
    // 创建游客用户（MongoDB，便于后续行为追踪）
    await patientService.createPatient({
      patientId: guestId,
      name: '游客用户',
      role: 'guest',
      deviceId: deviceId || 'unknown',
      isVerified: false
    });

    // 生成游客token（短期有效）
    const token = generatePatientToken(guestId, 'guest', 24 * 60 * 60);

    res.json({
      success: true,
      data: {
        accessToken: token,
        tokenType: "Bearer",
        expiresIn: 24 * 60 * 60, // 24小时
        user: {
          id: guestId,
          name: '游客用户',
          role: 'guest',
          isVerified: false,
          permissions: getPatientPermissions('guest')
        }
      }
    });

    console.log(`[游客访问] 设备: ${deviceId}`);

  } catch (error: any) {
    console.error("游客访问错误:", error);
    res.status(500).json({
      success: false,
      message: "访问服务异常"
    });
  }
});

// 获取患者信息
router.get("/me", async (req, res) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问令牌缺失'
      });
    }

    // 验证患者token（同步验证）
    let decoded: any;
    try {
      decoded = jwt.verify(token, PATIENT_AUTH_SECRET) as any;
    } catch {
      return res.status(403).json({ success: false, message: '访问令牌无效或已过期' });
    }

    if (decoded.type !== 'patient') {
      return res.status(403).json({ success: false, message: '令牌类型错误' });
    }

    const patient = await patientService.getPatientById(decoded.userId);
    if (!patient) {
      return res.status(404).json({ success: false, message: '用户信息不存在' });
    }

    res.json({
      success: true,
      data: {
        id: patient.patientId,
        name: patient.name,
        phone: patient.phone,
        role: patient.role,
        isVerified: patient.isVerified,
        permissions: decoded.permissions
      }
    });

  } catch (error: any) {
    console.error("获取患者信息错误:", error);
    res.status(500).json({
      success: false,
      message: "服务异常"
    });
  }
});

// 兼容小程序：POST /me 与 GET /me 相同逻辑
router.post("/me", async (req, res) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问令牌缺失'
      });
    }

    // 验证患者token（同步验证）
    let decoded: any;
    try {
      decoded = jwt.verify(token, PATIENT_AUTH_SECRET) as any;
    } catch {
      return res.status(403).json({ success: false, message: '访问令牌无效或已过期' });
    }

    if (decoded.type !== 'patient') {
      return res.status(403).json({ success: false, message: '令牌类型错误' });
    }

    const patient = await patientService.getPatientById(decoded.userId);
    if (!patient) {
      return res.status(404).json({ success: false, message: '用户信息不存在' });
    }

    res.json({
      success: true,
      data: {
        id: patient.patientId,
        name: patient.name,
        phone: patient.phone,
        role: patient.role,
        isVerified: patient.isVerified,
        permissions: decoded.permissions
      }
    });

  } catch (error: any) {
    console.error("获取患者信息错误:", error);
    res.status(500).json({
      success: false,
      message: "服务异常"
    });
  }
});

// 刷新患者token
router.post("/refresh-token", async (req, res) => {
  try {
    const { refreshToken } = req.body;
    
    if (!refreshToken) {
      return res.status(400).json({
        success: false,
        message: "刷新令牌不能为空"
      });
    }

    let decoded: any;
    try {
      decoded = jwt.verify(refreshToken, PATIENT_AUTH_SECRET) as any;
    } catch {
      return res.status(403).json({ success: false, message: '刷新令牌无效或已过期' });
    }

    if (decoded.type !== 'patient') {
      return res.status(403).json({ success: false, message: '令牌类型错误' });
    }

    const newToken = generatePatientToken(decoded.userId, decoded.role);
    res.json({
      success: true,
      data: {
        accessToken: newToken,
        tokenType: "Bearer",
        expiresIn: 30 * 24 * 60 * 60
      }
    });

  } catch (error: any) {
    console.error("刷新token错误:", error);
    res.status(500).json({
      success: false,
      message: "服务异常"
    });
  }
});

// 验证身份证信息
router.post("/verify-identity", async (req, res) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];
    const { name, idCard } = req.body;

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '访问令牌缺失'
      });
    }

    if (!name || !idCard) {
      return res.status(400).json({
        success: false,
        message: '姓名和身份证号不能为空'
      });
    }

    let decoded: any;
    try {
      decoded = jwt.verify(token, PATIENT_AUTH_SECRET) as any;
    } catch {
      return res.status(403).json({ success: false, message: '访问令牌无效' });
    }

    if (decoded.type !== 'patient') {
      return res.status(403).json({ success: false, message: '令牌类型错误' });
    }

    const patient = await patientService.getPatientById(decoded.userId);
    if (!patient) {
      return res.status(404).json({ success: false, message: '用户信息不存在' });
    }

    const isValid = idCard.length === 18 && /^\d{17}[\dX]$/.test(idCard);
    if (isValid) {
      await patientService.updatePatient(patient.patientId, { name, idCard, isVerified: true });
      return res.json({ success: true, message: '身份验证成功', data: { isVerified: true } });
    }

    res.status(400).json({ success: false, message: '身份证号格式不正确' });

  } catch (error: any) {
    console.error("身份验证错误:", error);
    res.status(500).json({
      success: false,
      message: "服务异常"
    });
  }
});

// 兼容小程序：退出登录（前端清理 token，这里直接返回成功）
router.post("/logout", (_req, res) => {
  return res.json({ success: true, message: '已退出登录' });
});

export default router;